package com.vito.act.tool;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Map;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vito.base.util.JSONUtil;
import com.vito.oa.act.constant.OaActContants;


/**
 *流程中的任务启动监听
 */
public class ActivitExecutionTaskStartListener implements Serializable, ExecutionListener {
	private static Logger log = LoggerFactory.getLogger(ActivitExecutionTaskStartListener.class);
	private static final long serialVersionUID = -7183785087582395585L;

	@Override
	public void notify(DelegateExecution execution) throws Exception {
		ExecutionEntity entity = (ExecutionEntity) execution;
		
		String nodeId = entity.getActivityId();	
		ProcessDefinitionImpl impl = entity.getProcessDefinition();
		ActivityImpl currentAct = impl.findActivity(nodeId);
		//重置驳回变量
		entity.setVariable(OaActContants.ROLL_BACK, OaActContants.BASE_STATE);
		//临时指派受理人
		Object assign = entity.getVariable(OaActContants.ASSIGN);
		entity.setVariable(OaActContants.ASSIGN,null);
		TaskDefinition taskDef = (TaskDefinition) currentAct.getProperty("taskDefinition");
		int assignCount = getMaxApprover(taskDef);
		if(assignCount == 0){
			return;
		}
		if(assign != null && !"".equals(assign)){
			if(ActivitiContants.ACTIVITI_TYPE_USERTASK.equals(currentAct.getProperty(ActivitiContants.ACTIVITI_TYPE))){
				String expressionText =  taskDef.getAssigneeExpression().getExpressionText();
				if(expressionText.startsWith("${") && expressionText.endsWith("}")){
					String variableName = expressionText.substring(2, expressionText.length()-1);
					if(assignCount == 1){
						entity.setVariable(variableName, assign);
					}else{
						if(assign instanceof String){
							assign = Arrays.asList(((String) assign).split(","));
						}
						entity.setVariable(OaActContants.MUTIL_ASSIGN, assign);
					}
					
				}
			}
		}
	}
	
	private int getMaxApprover(TaskDefinition task){
		Expression document = task.getDescriptionExpression();
		int maxApprover = 1;
		if(document != null){
			Map documentation = JSONUtil.convertString2Map(document.getExpressionText());
			if(documentation.containsKey("maxApprover")){
				maxApprover = (int)documentation.get("maxApprover");
			}
		}
		return maxApprover;
	}
	
}



